<?php
namespace app\api\logic;

use app\api\consDir\ErrorConst;
use app\api\services\CollectService;
use app\api\services\GoodsService;
use app\common\libs\Singleton;
use app\common\models\Shop\GoodsComment;
use app\common\utils\CommonUtil;

/**
 * 商品模块
 * Class ExchangeGoodsLogic
 * @package app\api\logic
 */
class ExchangeGoodsLogic extends BaseLogic
{
    use Singleton;

    public function search(): array
    {
        $arr = [
            '男装', '女装', '中山装',
        ];
        return ['rows' => $arr];
    }

    public function goodsComment($goodsId, $page, $pageSize, $isBad, $isImg): array
    {
        // ALTER TABLE `goods_comment` ADD INDEX `idx_GoodsId_Del` (`goods_id`, `deleted`);
        $goodsCommentCount = \think\facade\Db::table('goods_comment')->field([
            'COUNT(*) AS allCount',
            'SUM(CASE WHEN is_img = 1 THEN 1 ELSE 0 END) AS imgCount',
            'SUM(CASE WHEN is_bad = 1 THEN 1 ELSE 0 END) AS badCount',
        ])->where(['goods_id' => $goodsId, 'deleted' => 0])->find();
        $userComment = GoodsService::getInstance()->getComment(
            $goodsId,
            $isImg,
            $isBad,
            $page,
            $pageSize
        );
        return [
            'rows'              => $userComment,
            'goodsCommentCount' => $goodsCommentCount,
        ];
    }

    public function goodsDetail($exchangeType, $goodsId): array
    {
        $where = [
            'goods_id'      => $goodsId,
            'deleted'       => 0,
            'status'        => 1, # 1 在线 2下线
            // 'source'        => $source,
            'exchange_type' => $exchangeType,
        ];
        // 商品来源：1 日兮香商品 2 怡亚通商品
        $eg = \think\facade\Db::table('exchange_goods')
            ->where($where)
            ->find();
        // var_dump($eg);exit;
        if (empty($eg)) {
            CommonUtil::throwException(
                ErrorConst::NO_GOODS_ERROR,
                ErrorConst::NO_GOODS_ERROR_MSG
            );
        }
        // 1线下 2线上 3商品 4供应链
        $type = 3;
        if ($eg['source'] == 1) {
            $type      = 3;
            $goodsInfo = GoodsService::getInstance()->goodsDetail($goodsId);
        } elseif ($eg['source'] == 2) {
            $type      = 4;
            $goodsInfo = \app\api\logic\SupplyLogic::getInstance()->goodsDetail($goodsId);
            // var_dump($goodsInfo);exit;
        }
        if (empty($goodsInfo)) {
            CommonUtil::throwException(
                ErrorConst::NO_GOODS_ERROR,
                ErrorConst::NO_GOODS_ERROR_MSG
            );
        }
        // exchangeCoin_4_to_2
        $goodsInfo['exchangeCoin']  = number_format($eg['exchange_coin'], 2, '.', '');
        $goodsInfo['exchangeType']  = $eg['exchange_type'];
        $goodsInfo['exchangeCount'] = $eg['exchange_count'];

        $goodsInfo['isCollect'] = CollectService::getInstance()->getUserCollectStatus(
            $this->userinfo->id,
            $type,
            $goodsId);
        // $goodsInfo['commission']   = bcsub($goodsInfo['sellPrice'], $goodsInfo['costPrice'], 2);
        // $shopInfo                  = \app\api\services\ShopService::getInstance()->shopInfo($goodsInfo['shopId']);
        // $shopInfo['openStatus']    = 1;
        // $shopInfo['openWeek']      = '周一到周日';
        // $shopInfo['openTimeStart'] = '00:00';
        // $shopInfo['openTimeEnd']   = '23:00';
        // $shopInfo['goodsCount']    = \app\api\services\ShopService::getInstance()->shopGoodsCount($goodsInfo['shopId']);

        // ALTER TABLE `goods_comment` ADD INDEX `idx_GoodsId_Del` (`goods_id`, `deleted`);
        $goodsCommentCount = \think\facade\Db::table('goods_comment')->field([
            'COUNT(*) AS allCount',
            'SUM(CASE WHEN is_img = 1 THEN 1 ELSE 0 END) AS imgCount',
            'SUM(CASE WHEN is_bad = 1 THEN 1 ELSE 0 END) AS badCount',
        ])->where(['goods_id' => $goodsId, 'deleted' => 0])->find();

        $userComment = GoodsService::getInstance()->getComment($goodsId, 0, 0, 1, 3);

        $goodsSku = 1;
        if ($eg['source'] == 1) {
            $goodsSku = $this->goodsSkuSoruce1($exchangeType, $goodsId);
        } elseif ($eg['source'] == 2) {
            $goodsSku = $this->goodsSkuSoruce2($exchangeType, $goodsId);
        }

        $spec = GoodsService::getInstance()->specInfo($goodsId);

        $parameter = GoodsService::getInstance()->parameter($goodsId);

        $outLineDetail = GoodsService::getInstance()->goodsOutlineDetail($goodsId);

        return [
            'source'            => $eg['source'],
            'outLineDetail'     => $outLineDetail,
            'parameter'         => $parameter,
            'spec'              => $spec,
            // 'shopInfo'          => $shopInfo,
            'goodsSku'          => $goodsSku,
            'goodsInfo'         => $goodsInfo,
            'goodsCommentCount' => $goodsCommentCount,
            'userComment'       => $userComment,
        ];
    }

    private function goodsSkuSoruce1($exchangeType, $goodsId): array
    {
        $where = [
            ['e.goods_id', '=', $goodsId],
            ['e.exchange_type', '=', $exchangeType],
            ['e.deleted', '=', 0],
        ];
        $field = [
            'o.id',
            // 'o.sell_price',
            'o.cost_price',
            'o.sku_img',
            'o.goods_sales',
            // 'o.goods_inventory',
            'o.market_price',
            'o.sku_title',
            'o.spec_info',

            'e.id eid',
            'e.exchange_type',
            'e.exchange_coin',
            'e.exchange_price sell_price',
            'e.exchange_inventory goods_inventory',
            'e.exchange_count',
        ];
        $sku = \app\common\models\Shop\GoodsSku::getInstance()
            ->alias('o')
            ->join('exchange_goods_sku e', 'e.goods_sku_id = o.id', 'right')
            ->where($where)
            ->field($field)->select();
        $sku = empty($sku) ? [] : $sku->toArray();
        foreach ($sku as &$val) {
            // exchangeCoin_4_to_2
            $val['exchangeCoin'] = number_format($val['exchangeCoin'], 2, '.', '');
            $val['specArr']      = explode(';', $val['specInfo']);
            foreach ($val['specArr'] as $v) {
                $arr = explode('_', $v);

                $val['specIds'][$arr[0]] = $arr[1];
            }
        }
        return $sku;
    }

    private function goodsSkuSoruce2($exchangeType, $goodsId): array
    {
        $where = [
            ['e.goods_id', '=', $goodsId],
            ['e.exchange_type', '=', $exchangeType],
            ['e.deleted', '=', 0],
        ];
        $field = [
            'o.id',
            // 'o.suggest_price sell_price',
            'o.base_price cost_price',
            'o.sku_pic_url sku_img',
            'o.goods_sales',
            // 'o.stock goods_inventory',
            'o.official_distri_price market_price',
            // 'o.sku_title',
            'o.sku_property_list spec_info',

            'e.id eid',
            'e.exchange_type',
            'e.exchange_coin',
            'e.exchange_price sell_price',
            'e.exchange_inventory goods_inventory',
            'e.exchange_count',
        ];
        $sku = \app\common\models\Supply\SupplySku::getInstance()
            ->alias('o')
            ->join('exchange_goods_sku e', 'e.goods_sku_id = o.id', 'right')
            ->where($where)
            ->field($field)->select();
        $sku = empty($sku) ? [] : $sku->toArray();
        foreach ($sku as &$val) {
            // [{"specName":"规格","specValueName":"2g*12袋\/盒"},{"specName":"数量","specValueName":"3盒益生菌36袋【热卖】"}]
            $val['specInfo'] = is_string($val['specInfo']) ? json_decode($val['specInfo'], true) : $val['specInfo'];

            $specValueName = [];
            foreach ($val['specInfo'] as $pl) {
                if (isset($pl['specValueName'])) {
                    $specValueName[] = $pl['specValueName'];
                }
            }
            $vo['skuTitle'] = implode(' ;   ', $specValueName);
        }
        return $sku;
    }

    /**
     * [goodsList description]
     * @param  [type] $goodsType 1线下 2线上
     * @param  [type] $page      [description]
     * @param  [type] $pageSize  [description]
     * @param  array  $option    [
    'sort'         => $sort,
    'keyword'      => $keyword,
    'categoryId'   => $categoryId,
    'shopId'       => $shopId,
    'positionType' => $positionType,
    ]
     * @return [type]            [description]
     */
    public function goodsList($goodsType, $page, $pageSize, $option = []): array
    {
        $sort         = $option['sort'] ?? 0;
        $keyword      = $option['keyword'] ?? '';
        $categoryId   = $option['categoryId'] ?? 0;
        $shopId       = $option['shopId'] ?? 0;
        $positionType = $option['positionType'] ?? 0;
        $exchangeType = $option['exchangeType'] ?? 0;

        $field = $option['field'] ?? [
            '0 as gxzRate',
            '0 as shopId',

            'eg.goods_id as id',
            'eg.goods_id as goodsId',

            'eg.market_price as marketPrice',
            'eg.goods_sales as goodsSales',
            'eg.goods_tag as goodsTag',
            'eg.goods_service as goodsService',

            'eg.goods_img as goodsImg',
            'eg.goods_title as goodsTitle',
            'eg.exchange_price as sellPrice',
            'eg.exchange_inventory as goodsInventory',
            'eg.exchange_coin as exchangeCoin',
            'eg.exchange_type as exchangeType',
            'eg.exchange_count as exchangeCount',
            'eg.source as source',
        ];
        // goodsType 1线下 2线上
        // status 1 在线 2下线
        $where = [
            // ['g.status', '=', 1],
            // ['g.deleted', '=', 0],
            ['eg.deleted', '=', 0],
            ['eg.status', '=', 1],
        ];
        // 兑换类型 1 琅狼积分兑换 2 数字资产兑换 4 贡献值兑换
        if ( ! empty($exchangeType)) {
            $where[] = ['eg.exchange_type', '=', $exchangeType];
        }
        if ( ! empty($goodsType)) {
            $where[] = ['eg.goods_type', '=', (int) $goodsType];
        }
        if ( ! empty($categoryId)) {
            $where[] = ['eg.category_id1', '=', (int) $categoryId];
        }
        // if ( ! empty($shopId)) {
        //     $where[] = ['eg.shop_id', '=', (int) $shopId];
        // }
        if ( ! empty($keyword)) {
            $where[] = ['eg.goods_title', 'like', '%' . $keyword . '%'];
        }

        // positionType 0无 1社区商品 2推荐商品
        if ($positionType) {
            $where[] = ['eg.position_type', '=', $positionType];
        }
        // 0综合 1销量多到少 2价格低 3价格高
        $arr = [
            'g.sort desc, g.id desc',
            'g.goods_sales desc, g.id desc',
            'g.sell_price asc, g.id desc',
            'g.sell_price desc, g.id desc',
        ];
        $order = $arr[$sort] ?? $arr[0];
        $order = 'eg.sort desc, eg.id desc';
        // $list = \think\facade\Db::table('goods')
        //     ->alias('g')
        //     ->join('exchange_goods eg ', 'eg.goods_id= g.id')
        $list = \think\facade\Db::table('exchange_goods')
            ->alias('eg')
            ->where($where)
            ->field($field)
            ->limit(($page - 1) * $pageSize, $pageSize)
            ->order($order)
            ->select()->toArray();
        // var_dump($list);exit;
        foreach ($list as &$v) {
            // exchangeCoin_4_to_2
            $v['exchangeCoin'] = number_format($v['exchangeCoin'], 2, '.', '');
            // $v['gxz']          = GoodsService::getInstance()->getGxz($v['shopId'], $v['gxzRate'], $v['sellPrice']);
            isset($v['goodsTag']) && $v['goodsTag'] = empty($v['goodsTag']) ? [] : json_decode($v['goodsTag'], true);

            isset($v['goodsService']) && $v['goodsService'] = empty($v['goodsService']) ? [] : json_decode($v['goodsService'], true);
        }
        return [
            'debug' => [
                \think\facade\Db::table('goods')->getlastsql(),
            ],
            'rows'  => $list,
        ];
    }

    /**
     * 推荐商品
     * @param  [type]  $page     [description]
     * @param  [type]  $pageSize [description]
     * @return boolean           [description]
     */
    public function isLike($page, $pageSize, $option): array
    {
        $option['field'] = [
            'eg.goods_id as id',
            'eg.exchange_price as sellPrice',
            'eg.market_price as marketPrice',
            'eg.goods_img as goodsImg',
            'eg.goods_title as goodsTitle',
            'eg.exchange_coin as exchangeCoin',
            'eg.exchange_type as exchangeType',
            'eg.exchange_count as exchangeCount',
            'eg.source as source',

            // 'g.goods_sales as goodsSales',
            // 'g.goods_tag as goodsTag',
            // 'g.goods_service as goodsService',
            // 'eg.exchange_inventory as goodsInventory',
        ];
        // positionType 0无 1社区商品 2推荐商品
        $option['positionType'] = 2;

        $page = $this->goodsList(
            0,
            $page,
            $pageSize,
            $option);
        return $page;
    }

    /**
     * 商品分类
     * @param  [type] $categoryType 1线下 2线上
     * @return [type]               [description]
     */
    public function goodsCategory($categoryType, $pid = 0): array
    {
        $rows = GoodsService::getInstance()->goodsCategory(
            $categoryType,
            $pid);
        return ['rows' => $rows];
    }
}
